
#import "MHToolUtils.h"

#define mlx_version @"Version"


#define UIWindowLevelPopOver 10000000000

static MHToolUtils *_instance;

@interface MHPopOverRootViewController : UIViewController

@property (nonatomic) BOOL statusBarHidden;

@property (nonatomic) UIStatusBarStyle statusBarStyle;

@end

@implementation MHPopOverRootViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.view.frame = MH_SCREEN_BOUNDS;
        self.view.backgroundColor = [UIColor clearColor];
    }
    
    return self;
}

- (BOOL)prefersStatusBarHidden {
    return _statusBarHidden;
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return _statusBarStyle;
}

- (BOOL)shouldAutorotate {
    return YES;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    UIInterfaceOrientationMask supportedInterfaceOrientations;
    UIInterfaceOrientation statusBarOrientation = [UIApplication sharedApplication].statusBarOrientation;
    supportedInterfaceOrientations = [self getInterfaceOrientations:statusBarOrientation];
    
    return supportedInterfaceOrientations;
}

- (UIInterfaceOrientationMask)getInterfaceOrientations:(UIInterfaceOrientation)interfaceOrientation {
    UIInterfaceOrientationMask supportedInterfaceOrientations;
    
    switch (interfaceOrientation) {
        case UIInterfaceOrientationPortrait:
        case UIInterfaceOrientationUnknown:
            supportedInterfaceOrientations = UIInterfaceOrientationMaskPortrait;
            break;
        case UIInterfaceOrientationLandscapeLeft:
            supportedInterfaceOrientations = UIInterfaceOrientationMaskLandscapeLeft;
            break;
        case UIInterfaceOrientationLandscapeRight:
            supportedInterfaceOrientations = UIInterfaceOrientationMaskLandscapeRight;
            break;
        case UIInterfaceOrientationPortraitUpsideDown:
            supportedInterfaceOrientations = UIInterfaceOrientationMaskPortraitUpsideDown;
            break;
    }
    
    return supportedInterfaceOrientations;
}

@end


@interface MHToolUtils()
@property(nonatomic,strong) MHUserModel *userModel;
@end

@implementation MHToolUtils
+(instancetype)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (_instance == nil) {
            _instance = [super allocWithZone:zone];
        }
    });
    return _instance;
}
+(instancetype)shareTools{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    });
    return _instance;
}
// 为了严谨，也要重写copyWithZone 和 mutableCopyWithZone
-(id)copyWithZone:(NSZone *)zone{
    return _instance;
}
-(id)mutableCopyWithZone:(NSZone *)zone{
    return _instance;
}
+(MHAppDelegate *)getAppDelegate{
    return [UIApplication sharedApplication].delegate;
}
@end

@implementation NSObject (Model)
/** 获取数据*/
+(id)getSqliteModel:(NSString *)where class:(Class)Class{
    NSArray* arr = [Class bg_find:nil where:where];
    if (arr.count) {
        return arr.firstObject;
    }
    return nil;
}
/** 保存数据*/
-(void)saveSqliteModel{
    [self bg_saveOrUpdate];
}
+(void)saveUserModel:(id)userModel{
    if (!userModel) return;
#ifdef userModel
    MHUserModel *firstModel = [MHToolUtils shareTools].userModel;
//    这句表示必须不是同一个人
    if (firstModel && ![userModel.sellerPhoneNum isEqualToString:firstModel.sellerPhoneNum]) {//这句是覆盖原来的用户的登陆信息
        firstModel.isLastLogin = NO;
        [firstModel bg_saveOrUpdate];
        //            [MHToolUtils shareTools].userModel = nil;
    }
    if (userModel.isLastLogin) {
        [MHToolUtils shareTools].userModel = userModel;
    }else{
//        [MHToolUtils shareTools].userModel = nil;
    }
    [userModel bg_saveOrUpdate];
#endif
}
+(MHUserModel *)getSqliteUserModel:(NSString *)mobile{
    NSString* where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"sellerPhoneNum"),bg_sqlValue(mobile)];
    return [self getSqliteUserModelWhere:where];
}
+(MHUserModel *)getSqliteUserModelWhere:(NSString *)where{
    NSArray* arr = [self bg_find:nil where:where];
    if (arr.count) {
        return arr.firstObject;
    }
    return nil;
}
+(MHUserModel *)getMemoryUserModel{
    MHToolUtils *tools = [MHToolUtils shareTools];
    return tools.userModel;
}
+(MHUserModel *)isAlreadyLastLogin{
    NSString* where = [NSString stringWithFormat:@"where %@=%@ order by %@ desc",bg_sqlKey(@"isLastLogin"),bg_sqlValue(@YES),bg_sqlKey(@"bg_updateTime")];
    MHUserModel *userModel =  [self getSqliteUserModelWhere:where];
    [MHToolUtils shareTools].userModel = userModel;
    return userModel;
}
+(MHUserModel *)getSqliteLatestTimeDate{
    NSString *where = [NSString stringWithFormat:@"order by %@ desc",bg_sqlKey(@"bg_updateTime")];
    return [self getSqliteUserModelWhere:where];
}
+(BOOL)isNewFirstLaunchApp{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    return [defaults objectForKey:kAppVersion] ? NO : YES;
}
+(BOOL)isNewVersinLaunchApp{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *sanboxVersion = [defaults objectForKey:mlx_version] ? [defaults objectForKey:mlx_version]: @"0.0";
    if ([kAppVersion compare:sanboxVersion] == NSOrderedDescending) {
        [defaults setObject:kAppVersion forKey:mlx_version];
        [defaults synchronize];
        return YES;
    }
    return NO;
}
+ (NSString *)appName {
    //   NSString *appName = NSLocalizedStringFromTable(@"CFBundleDisplayName", @"InfoPlist.strings", @"");
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Name = [infoDictionary objectForKey:@"CFBundleName"];
    return app_Name;
}

//获取拼音首字母(传入汉字字符串, 返回大写拼音首字母)
+ (NSString *)firstPinyinLetterOfString:(NSString *)aString
{
    if (aString.length == 0)
        return nil;
    
    //首字符就是字母
    unichar C = [aString characterAtIndex:0];
    if((C<= 'Z' && C>='A') || (C <= 'z' && C >= 'a')) {
        //转化为大写拼音
        NSString *pinYin = [[aString substringToIndex:1] capitalizedString];
        //获取并返回首字母
        return pinYin;
    }
    
    //转成了可变字符串
    NSMutableString *str = [NSMutableString stringWithString:[aString substringToIndex:1]];
    //先转换为带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    //再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
    //转化为大写拼音
    NSString *pinYin = [str capitalizedString];
    //获取并返回首字母
    return [pinYin substringToIndex:1];
}

+ (UIWindow *)popOverWindow {
    static UIWindow *popOverWindow;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        popOverWindow = [[UIWindow alloc] initWithFrame:MH_SCREEN_BOUNDS];
        popOverWindow.backgroundColor = [UIColor clearColor];
        popOverWindow.windowLevel = UIWindowLevelPopOver;
        popOverWindow.hidden = YES;
        popOverWindow.rootViewController = [[MHPopOverRootViewController alloc] initWithNibName:nil bundle:nil];
    });
    return popOverWindow;
}
+ (void)addViewToPopOverWindow:(UIView *)view {
    MHPopOverRootViewController *vc = (MHPopOverRootViewController *)[self popOverWindow].rootViewController;
    vc.statusBarStyle = [UIApplication sharedApplication].statusBarStyle;
    vc.statusBarHidden = [UIApplication sharedApplication].statusBarHidden;
    [vc.view addSubview:view];
    [self popOverWindow].hidden = NO;
    [vc setNeedsStatusBarAppearanceUpdate];
}
+ (void)removeViewFromPopOverWindow:(UIView *)view {
    MHPopOverRootViewController *vc = (MHPopOverRootViewController *)[self popOverWindow].rootViewController;
    [view removeFromSuperview];
    if (vc.view.subviews.count == 0) {
        [self popOverWindow].hidden = YES;
    }
}

@end
